import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

# 示例数据
data = {
    'age': [25, 45, 35, 50, 23, 31, 22, 35, 42, 51],
    'income': [50000, 100000, 75000, 120000, 40000, 60000, 45000, 80000, 110000, 130000]
}
df = pd.DataFrame(data)

# 创建K均值模型
kmeans = KMeans(n_clusters=3)
kmeans.fit(df)

# 预测聚类结果
df['cluster'] = kmeans.labels_

# 可视化聚类结果
plt.scatter(df['age'], df['income'], c=df['cluster'], cmap='viridis')
plt.xlabel('Age')
plt.ylabel('Income')
plt.title('Customer Segments')
plt.show()

print(df)